package com.lin.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.reggie.Dto.DishDto;
import com.lin.reggie.entity.Category;
import com.lin.reggie.entity.Dish;
import com.lin.reggie.entity.DishFlavor;
import com.lin.reggie.entity.Employee;
import com.lin.reggie.service.CategoryService;
import com.lin.reggie.service.DishFlavorService;
import com.lin.reggie.service.DishService;
import com.lin.reggie.service.SetmealService;
import com.lin.reggie.utils.R;
import jdk.nashorn.internal.ir.SetSplitState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.security.auth.callback.LanguageCallback;
import java.security.PublicKey;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author lin
 * @since 2022-05-26
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    DishService dishService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SetmealService setmealService;

    //添加菜品方法
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());


        dishService.saveWithFlavor(dishDto);

        return R.success("添加菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page ,int pageSize,String name){
        //1.ajax传递请求参数
        log.info("page={},pageSize={},name={}",page,pageSize,name);

        //构造分页构造器
        Page<Dish> pageInfos = new Page<Dish>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();


        //构造一个条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加一个排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行查询,page方法是分页查询，传入构造的分页器和条件构造器
        dishService.page(pageInfos, queryWrapper);
        //对象拷贝
//        System.out.println(pageInfos.toString());
        BeanUtils.copyProperties(pageInfos,dishDtoPage,"records");

        List<Dish> records = pageInfos.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            //遍历pageinfos中的records，再遍历其中的id和name到dishdto，
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get (@PathVariable Long id){

        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);

        return R.success(byIdWithFlavor);
    }
    /**
     * 将更改的菜品信息update
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        return R.success("更新成功");
    }

    /**
     * 批量修改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable("status") Integer status,@RequestParam List<Long> ids) {
        //log.info("status:{}",status);
        //log.info("ids:{}",ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(ids != null, Dish::getId, ids);
        //根据数据进行批量查询
        List<Dish> list = dishService.list(queryWrapper);

        for (Dish dish : list) {
            if (dish != null) {
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("售卖状态修改成功");
    }


    /**
     * 套餐批量删除和单个删除
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam("ids") List<Long> id) {
        //删除菜品  这里的删除是逻辑删除
        dishService.removewithFlavors(id);
        //删除菜品对应的口味  也是逻辑删除
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DishFlavor::getDishId, id);
        dishFlavorService.remove(queryWrapper);
        return R.success("菜品删除成功");
    }

    /**
     * 查询菜品的信息，给添加套餐使用
     * @param dish
     * @return
     */

//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//
//        //构造条件构造器
//        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
//        return R.success(list);
//    }

    /**
     * 改造批量查询菜品，同时返回带有口味信息的菜品，可以同时给添加套餐，和手机端显示菜品页面使用
     *
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //这个可以categoryId但是为了代码通用性更强，这个理直接使用Dish类来接收

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1的菜品
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);

        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list =dishService.list(dishLambdaQueryWrapper);

        //进行集合的泛型转化
        List<DishDto> collect = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //为一个新的对象赋值，一定要考虑你为它赋过几个值，否则你自己都不知道就返回了null的
            //为dishDto对象的基本属性拷贝
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String name = category.getName();
                dishDto.setCategoryName(name);
            }
            //为Dishdto赋值flavors属性
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //创建条件查询对象
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(collect);
    }
}

